package com.wyh.captcha.captchaController;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.wyh.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 王圆豪
 * Date: 2025-07-05
 * Time: 16:33
 */
@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    private final static Long VALID_TIME = 30 * 60 * 1000L;

    /**
     * 返回验证码
     * @param response
     * @param session
     * @throws IOException
     */
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(
                captchaProperties.getWidth(),
                captchaProperties.getHeight());
        String code = lineCaptcha.getCode();
        session.setAttribute("key",code);
        session.setAttribute("date",new Date());
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().close();
    }

    /**
     * 校验验证码
     * @param captcha
     * @param session
     * @return
     */
    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session){
        if (!StringUtils.hasText(captcha)){
            return false;
        }

        String key = (String) session.getAttribute("key");
        Date data = (Date) session.getAttribute("date");
        if (key.equalsIgnoreCase(captcha) &&
                System.currentTimeMillis()-data.getTime()<VALID_TIME){
            return true;
        }
        return false;
    }
}
